﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.BusinessEntity.YunZhiJia;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.ConstrainedExecution;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using static Kingdee.K3.FIN.Core.Match.AR_WriteOffStencil;
using static LiMinCRMPlugin.InterfaceDocking.Common;
using static LiMinCRMPlugin.InterfaceDocking.ReceivebillModel;

namespace LiMinCRMPlugin.InterfaceDocking
{
    /// <summary>
    /// 收款单审核插件
    /// </summary>
    /// <remarks>
    /// 功能：收款单在创建审核后自动传到CRM。
    /// 创建人：mey
    /// 创建日期：2024.3.23
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    /// 
    [Description("收款单审核同步至CRM")]
    [HotUpdate]
    public class ReceivebillToCRM : AbstractOperationServicePlugIn
    {
        //OnPreparePropertys 数据加载前，确保需要的属性被加载
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            //编码
            e.FieldKeys.Add("FBillNo");
            //单据类型
            e.FieldKeys.Add("FBillTypeID");
            //付款单位类型
            e.FieldKeys.Add("FPAYUNITTYPE");
            //付款单位
            e.FieldKeys.Add("FPAYUNIT");
            //业务日期
            e.FieldKeys.Add("FDATE");
            //往来单位类型
            e.FieldKeys.Add("FCONTACTUNITTYPE");
            //往来单位
            e.FieldKeys.Add("FCONTACTUNIT");
            //币别
            e.FieldKeys.Add("FCURRENCYID");
            //实收金额
            e.FieldKeys.Add("FREALRECAMOUNTFOR");
            //备注
            e.FieldKeys.Add("FREMARK");
            //收款组织
            e.FieldKeys.Add("FPAYORGID");
            //结算组织
            e.FieldKeys.Add("FSETTLEORGID");
            //销售组织
            e.FieldKeys.Add("FSALEORGID");
            //销售部门
            e.FieldKeys.Add("FSALEDEPTID");
            //销售员
            e.FieldKeys.Add("F_DEV_Saler");
            //是否定制（核销方式）
            e.FieldKeys.Add("F_DEV_OffsetE");
            //是否淡储
            e.FieldKeys.Add("F_DEV_SurviveE");
            //销售订单编号
            e.FieldKeys.Add("F_DEV_OrderNoE");
            //结算方式
            e.FieldKeys.Add("FSETTLETYPEID");
            //收款用途
            e.FieldKeys.Add("FPURPOSEID");
            //手续费
            e.FieldKeys.Add("FHANDLINGCHARGEFOR");
            //我方银行账号
            e.FieldKeys.Add("FACCOUNTID");
            //同步CRM状态
            e.FieldKeys.Add("F_DEV_FSTATUS");

            //同步CRM状态
            e.FieldKeys.Add("FREALRECAMOUNTFOR_D");
            //同步CRM状态
            e.FieldKeys.Add("F_DEV_CRMNumber");

            //核销方式
            e.FieldKeys.Add("F_RDLV_WriteOff");
            //汇率
            e.FieldKeys.Add("FEXCHANGERATE");
            //保证金
            e.FieldKeys.Add("F_RDLV_Bond");
            //转销
            e.FieldKeys.Add("FCreatorId");

            //销售主体
            e.FieldKeys.Add("F_QLTK_saler");
            //期初
            e.FieldKeys.Add("FISINIT");
            e.FieldKeys.Add("FRECTOTALAMOUNTFOR");//应收金额

            //回款类型
            e.FieldKeys.Add("F_QLTK_CollectionType");
            e.FieldKeys.Add("FCOMMENT");
           
        }
        /// <summary>
        /// 事务结束后事件
        /// </summary>
        /// <param name="e"></param>
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);

            //读取全部的单据,for循环,转换成DynamicObject类型
            foreach (DynamicObject entity in e.DataEntitys)
            {

                DataTable dt = APISetting();
                string httpUrl = dt.Rows[0]["F_RDLV_URL"].ToString();
                string httpSystemId = dt.Rows[0]["F_RDLV_SystemId"].ToString();
                string httpPassword = dt.Rows[0]["F_RDLV_Password"].ToString();

                string FISINIT = entity["ISINIT"].ToString();//是起初单据
                //不是期初FISINIT == "0"
                if (1 == 1)
                {
                    string FSTATUS = Convert.ToString(entity["F_DEV_FSTATUS"]);//同步CRM状态 空-未同步，成功-同步成功，失败-同步失败
                    string FID = Convert.ToString(entity["Id"]);//内码                      
                    string Number = entity["BillNo"].ToString();//编码


                    string UserAccount = "CRM";//用户账号
                    //DynamicObject User = entity["FCreatorId"] as DynamicObject;//用户
                    //if (User != null)
                    //{
                    //    UserAccount = Convert.ToString(User["UserAccount"]);
                    //}

                    DynamicObject Fpayorg = entity["FPAYORGID"] as DynamicObject;//收款组织 skzz
                    string FpayorgId = "";//收款组织
                    if (Fpayorg != null)
                    {
                        FpayorgId = Convert.ToString(Fpayorg["Number"]);//收款组织

                    }

                    //校验组织在此视图内才回传
                    string CRM_V_Organizations = string.Format(@"/*dialect*/  select * from CRM_V_Organizations where FNUMBER='" + FpayorgId + "'");
                    DataTable dt_Organizations = DBServiceHelper.ExecuteDataSet(this.Context, CRM_V_Organizations).Tables[0];
                    if (dt_Organizations != null && dt_Organizations.Rows.Count > 0)
                    {
                        DynamicObject FSettleOrg = entity["SETTLEORGID"] as DynamicObject;//结算组织 jszz
                        string FSettleOrgId = "";//结算组织
                        if (FSettleOrg != null)
                        {
                            FSettleOrgId = Convert.ToString(FSettleOrg["Number"]);//结算组织

                        }

                        DynamicObject FSaleOrg = entity["SALEORGID"] as DynamicObject;//销售组织 skzz
                        string FSaleOrgId = "";//销售组织
                        if (FSaleOrg != null)
                        {
                            FSaleOrgId = Convert.ToString(FSaleOrg["Number"]);//销售组织

                        }

                        string Fdate = "";
                        if (entity["DATE"] != null && entity["DATE"].ToString() != "")
                        {
                            Fdate = Convert.ToDateTime(entity["DATE"]).ToString("yyyy-MM-dd");//业务日期 ywrq
                        }



                        DynamicObject FPayUnit = entity["PAYUNIT"] as DynamicObject;//往来单位 wldw
                        string FPayUnitId = "";//往来单位
                        if (FPayUnit != null)
                        {
                            FPayUnitId = Convert.ToString(FPayUnit["Number"]);//往来单位

                        }
                        if (FPayUnitId != "")
                        {
                            string payUnit_S = string.Format(@"/*dialect*/  select * from T_BD_CUSTOMER where FNUMBER='" + FPayUnitId + "'");
                            DataTable dt_S = DBServiceHelper.ExecuteDataSet(this.Context, payUnit_S).Tables[0];//F_DEV_CRMId
                            if (dt_S != null && dt_S.Rows.Count > 0)
                            {
                                FPayUnitId = dt_S.Rows[0]["F_RDLV_CRMId"].ToString();
                            }


                        }


                        DynamicObject FContactUnit = entity["CONTACTUNIT"] as DynamicObject;//付款单位 fkdw
                        string FContactUnitId = "";//付款单位
                        if (FContactUnit != null)
                        {
                            FContactUnitId = Convert.ToString(FContactUnit["Number"]);//付款单位

                        }
                        if (FContactUnitId != "")
                        {
                            string payUnit_S = string.Format(@"/*dialect*/  select * from T_BD_CUSTOMER where FNUMBER='" + FContactUnitId + "'");
                            DataTable dt_S = DBServiceHelper.ExecuteDataSet(this.Context, payUnit_S).Tables[0];//F_DEV_CRMId
                            if (dt_S != null && dt_S.Rows.Count > 0)
                            {
                                FContactUnitId = dt_S.Rows[0]["F_RDLV_CRMId"].ToString();
                            }


                        }


                        DynamicObject FCurrenCy = entity["CURRENCYID"] as DynamicObject;//币别 bb
                        string FCurrenCyId = "";//币别
                        if (FCurrenCy != null)
                        {
                            FCurrenCyId = Convert.ToString(FCurrenCy["Name"]);//币别

                        }

                        DynamicObject FSaleDept = entity["SALEDEPTID"] as DynamicObject;//销售部门 xsbm  传入：OA部门姓名
                        string FSaleDeptId = "";//销售部门
                        if (FSaleDept != null)
                        {
                            FSaleDeptId = Convert.ToString(FSaleDept["Number"]);//销售部门

                        }

                        DynamicObject FSaler = entity["F_DEV_Saler"] as DynamicObject;//销售员 xsy   传入：OA人员姓名
                        string FSalerId = "";//销售员
                        if (FSaler != null)
                        {
                            FSalerId = Convert.ToString(FSaler["FStaffNumber"]);//销售员

                        }


                        string yxlsbm1 = entity["F_DEV_CRMNumber"].ToString();//CRM编码

                        string FRemark = entity["FREMARK"].ToString();//备注 bz

                        DynamicObject FBillType = entity["BillTypeID"] as DynamicObject;//单据类型
                        string FBillTypeId = "";//单据类型
                        if (FBillType != null)
                        {
                            FBillTypeId = Convert.ToString(FBillType["Name"]);//单据类型

                        }

                        decimal FEXCHANGERATE = Convert.ToDecimal(entity["EXCHANGERATE"]);//汇率


                        string SaleBodyNo = "";//销售主体编码
                        string SaleBodyName = "";//销售主体名称
                        DynamicObject SaleBody = entity["F_QLTK_saler"] as DynamicObject;//销售主体
                        if (SaleBody != null)
                        {
                            SaleBodyNo = Convert.ToString(SaleBody["Number"]); //销售主体编码
                            SaleBodyName = Convert.ToString(SaleBody["Name"]);//销售主体名称
                        }


                        string CollectionType = entity["F_QLTK_CollectionType"].ToString();//回款类型
                        


                        //明细
                        DynamicObjectCollection FEntity = entity["RECEIVEBILLENTRY"] as DynamicObjectCollection;
                        string messbox = "";
                        foreach (DynamicObject Fe in FEntity)
                        {
                            decimal FhandlingChage = 0;//手续费
                            string FSettleTypeId = "";//结算方式
                            string FpurPoseId = "";//收款用途
                            string FaccountId = "";//我方银行账号
                            string FEntryId = Fe["ID"].ToString();//明细内码
                            string FSEQ = Fe["SEQ"].ToString();//行号
                            DynamicObject FSettleType = Fe["SETTLETYPEID"] as DynamicObject;//结算方式

                            if (FSettleType != null)
                            {
                                FSettleTypeId = Convert.ToString(FSettleType["Number"]);//结算方式

                            }
                            DynamicObject FpurPose = Fe["PURPOSEID"] as DynamicObject;//收款用途

                            if (FpurPose != null)
                            {
                                FpurPoseId = Convert.ToString(FpurPose["Number"]);//收款用途

                            }
                            decimal FrealrecaMountFor = Convert.ToDecimal(Fe["RECTOTALAMOUNTFOR"]); //应收金额

                            FhandlingChage = FhandlingChage + Convert.ToDecimal(Fe["HANDLINGCHARGEFOR"]); //手续费

                            decimal FREALRECAMOUNTFOR = Math.Round(Convert.ToDecimal(Fe["REALRECAMOUNTFOR"]), 2); //实收金额

                            DynamicObject Faccount = Fe["ACCOUNTID"] as DynamicObject;//我方银行账号

                            if (Faccount != null)
                            {
                                FaccountId = Convert.ToString(Faccount["Id"]);//我方银行账号

                            }


                            string Survive = Fe["F_DEV_SurviveE"].ToString();//是否淡储款 sfdck  枚举：[0:否,1:是]

                            string Offset = Fe["F_DEV_OffsetE"].ToString();//是否定制（核销方式） hs  枚举：[0:非定制（按客户核销））,1:定制（按单核销）,2:非定制（自动核销）]

                            string OrderNo = Fe["F_DEV_OrderNoE"].ToString();//销售订单编号 xsddbh
                            string WriteOff = Fe["F_RDLV_WriteOff"].ToString();//核销方式  hxfs

                            string Bond = Fe["F_RDLV_Bond"].ToString();//是否保证金

                            string FCOMMENT = Fe["COMMENT"].ToString();//

                            #region 插入更新赋值
                            mainTable mainTable1 = new mainTable()
                            {
                                bdnm = FID,//表单内码
                                skzz = FpayorgId,//收款组织
                                jszz = FSettleOrgId,//结算组织
                                xszz = FSaleOrgId,//销售组织
                                ywrq = Fdate,//业务日期
                                wldw = FPayUnitId,//往来单位
                                fkdw = FContactUnitId,//付款单位
                                bb = FCurrenCyId,//币别
                                xsbm = FSaleDeptId,//销售部门
                                xsy = FSalerId,//销售员
                                sfdck = Survive,//是否淡储款 枚举：[0:否,1:是]
                                sfdzhxfs = Offset,// 是否定制（核销方式） 枚举：[0:非定制（按客户核销））,1:定制（按单核销）,2:非定制（自动核销）]
                                xsddbh = OrderNo,//销售订单编号
                                jsfs = FSettleTypeId,//结算方式

                                skyt = FpurPoseId,//收款用途

                                ysje = FrealrecaMountFor,//应收金额

                                sxf = FhandlingChage,//手续费
                                wfyxzh = FaccountId,//我方银行账号

                                bz = FRemark,//手续费
                                djlx = FBillTypeId,//单据类型
                                mxid = FEntryId,
                                ssje = FREALRECAMOUNTFOR,
                                yxlsbm = yxlsbm1,
                                hxfs = WriteOff,
                                sfbzj = Bond,
                                hl = FEXCHANGERATE,
                                xszt = SaleBodyNo,
                                mxbz=FCOMMENT,
                                hklx= CollectionType


                            };
                            //操作人员信息
                            operationinfo operationinfo1 = new operationinfo()
                            {
                                operatorAbAb = UserAccount,
                                operationDate = DateTime.Now.ToString("yyyy-MM-dd"),
                                operationTime = DateTime.Now.ToString("HH:mm:ss")
                            };

                            String currentTimeTamp = getTimestamp();
                            String md5Source = httpSystemId + httpPassword + currentTimeTamp;
                            String md5OfStr = Md5(md5Source).ToLower();


                            Header header1 = new Header()
                            {
                                systemid = httpSystemId,
                                currentDateTime = currentTimeTamp,
                                Md5 = md5OfStr
                            };

                            Data data = new Data()
                            {
                                operationinfo = operationinfo1,
                                mainTable = mainTable1
                            };

                            List<Data> datas = new List<Data>();
                            datas.Add(data);


                            DataHeader dataHeader = new DataHeader()
                            {
                                data = datas,
                                header = header1
                            };
                            var json = JsonConvert.SerializeObject(dataHeader);
                            json = json.ToString().Replace("operatorAbAb", "operator");
                            #endregion

                            #region 查询赋值
                            ReceivebillSelectModel.mainTable mainTable2 = new ReceivebillSelectModel.mainTable()
                            {
                                mxid = FEntryId,
                                bdnm = FID,
                                djlx = FBillTypeId
                            };
                            //操作人员信息
                            ReceivebillSelectModel.operationinfo operationinfo2 = new ReceivebillSelectModel.operationinfo()
                            {
                                operatorAbAb = UserAccount,

                            };
                            ReceivebillSelectModel.Header header2 = new ReceivebillSelectModel.Header()
                            {
                                systemid = httpSystemId,
                                currentDateTime = currentTimeTamp,
                                Md5 = md5OfStr
                            };
                            ReceivebillSelectModel.DataHeader dataHeader1 = new ReceivebillSelectModel.DataHeader()
                            {
                                operationinfo = operationinfo2,
                                mainTable = mainTable2,
                                header = header2
                            };

                            var jsonS = JsonConvert.SerializeObject(dataHeader1);
                            jsonS = jsonS.ToString().Replace("operatorAbAb", "operator");
                            #endregion

                            //查询是否存在
                            var httpJson = GlobalParameters.PostToPushGroupNews(httpUrl + "/cube/restful/interface/getDataByPK/select_receipt", jsonS);

                            var arrresult = JsonConvert.DeserializeObject<SortedDictionary<string, object>>(httpJson);//转换
                            var MainTable = JsonConvert.DeserializeObject<SortedDictionary<string, object>>(arrresult["result"].ToString());//转换


                            if (MainTable.Count == 0)//
                            {

                                var AddJson = GlobalParameters.PostToPushGroupNews(httpUrl + "/cube/restful/interface/saveOrUpdateModeData/create_receipt", json);

                                var Addresult = JsonConvert.DeserializeObject<GlobalParameters.ReturnJson>(AddJson);//转换


                                if (Addresult.status == "1")
                                {
                                    #region 收款单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                    Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                    interfaceLog.FBILLNO = Number;
                                    interfaceLog.FBILLID = FEntryId;
                                    interfaceLog.FDATE = System.DateTime.Now;
                                    interfaceLog.FINTERNAME = "收款单";
                                    interfaceLog.FInvokeType = "收款单新增";
                                    interfaceLog.Ftoken = "";
                                    interfaceLog.FSTATUS = "成功";
                                    interfaceLog.FRequsetData = json.ToString();
                                    interfaceLog.FReturnData = AddJson.ToString();
                                    interfaceLog.FRequest = json.ToString();
                                    interfaceLog.FReturn = AddJson.ToString();
                                    string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                    List<string> sqlList = new List<string>();
                                    if (!string.IsNullOrEmpty(LogSql))
                                    {
                                        sqlList.Add(LogSql);
                                    }
                                    //更新单据
                                    string updateSql = string.Format(@"/*dialect*/ update T_AR_RECEIVEBILLENTRY set F_RDLV_CRMDate='{0}',F_RDLV_CRMStatus='{1}' 
                    where fentryid={2}", DateTime.Now, interfaceLog.FSTATUS, FEntryId);

                                    sqlList.Add(updateSql);
                                    DBServiceHelper.ExecuteBatch(this.Context, sqlList);


                                    #endregion
                                }
                                else
                                {
                                    #region 收款单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                    Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                    interfaceLog.FBILLNO = Number;
                                    interfaceLog.FBILLID = FEntryId;
                                    interfaceLog.FDATE = System.DateTime.Now;
                                    interfaceLog.FINTERNAME = "收款单";
                                    interfaceLog.FInvokeType = "收款单新增";
                                    interfaceLog.Ftoken = "";
                                    interfaceLog.FSTATUS = "失败";
                                    interfaceLog.FRequsetData = json.ToString();
                                    interfaceLog.FReturnData = AddJson.ToString();
                                    interfaceLog.FRequest = json.ToString();
                                    interfaceLog.FReturn = AddJson.ToString();
                                    string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                    List<string> sqlList = new List<string>();
                                    if (!string.IsNullOrEmpty(LogSql))
                                    {
                                        sqlList.Add(LogSql);
                                    }

                                    //更新单据
                                    string updateSql = string.Format(@"/*dialect*/ update T_AR_RECEIVEBILLENTRY set F_RDLV_CRMDate='{0}',F_RDLV_CRMStatus='{1}' 
                    where fentryid={2}", DateTime.Now, interfaceLog.FSTATUS, FEntryId);

                                    sqlList.Add(updateSql);
                                    DBServiceHelper.ExecuteBatch(this.Context, sqlList);

                                    messbox = messbox + "," + FSEQ;
                                    #endregion
                                }

                            }
                            else
                            {
                                //cube / restful /interface/saveOrUpdateModeData/update_Transportation_area
                                var UpdateJson = GlobalParameters.PostToPushGroupNews(httpUrl + "/cube/restful/interface/saveOrUpdateModeData/update_receipt", json);

                                var Updateresult = JsonConvert.DeserializeObject<GlobalParameters.ReturnJson>(UpdateJson);//转换

                                if (Updateresult.status == "1")
                                {
                                    #region 收款单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                    Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                    interfaceLog.FBILLNO = Number;
                                    interfaceLog.FBILLID = FEntryId;
                                    interfaceLog.FDATE = System.DateTime.Now;
                                    interfaceLog.FINTERNAME = "收款单";
                                    interfaceLog.FInvokeType = "收款单更新";
                                    interfaceLog.Ftoken = "";
                                    interfaceLog.FSTATUS = "成功";
                                    interfaceLog.FRequsetData = json.ToString();
                                    interfaceLog.FReturnData = UpdateJson.ToString();
                                    interfaceLog.FRequest = json.ToString();
                                    interfaceLog.FReturn = UpdateJson.ToString();
                                    string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                    List<string> sqlList = new List<string>();
                                    if (!string.IsNullOrEmpty(LogSql))
                                    {
                                        sqlList.Add(LogSql);
                                    }
                                    //更新单据
                                    string updateSql = string.Format(@"/*dialect*/ update T_AR_RECEIVEBILLENTRY set F_RDLV_CRMDate='{0}',F_RDLV_CRMStatus='{1}' 
                    where fentryid={2}", DateTime.Now, interfaceLog.FSTATUS, FEntryId);

                                    sqlList.Add(updateSql);
                                    DBServiceHelper.ExecuteBatch(this.Context, sqlList);

                                    #endregion
                                }
                                else
                                {
                                    #region 收款单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                    Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                    interfaceLog.FBILLNO = Number;
                                    interfaceLog.FBILLID = FEntryId;
                                    interfaceLog.FDATE = System.DateTime.Now;
                                    interfaceLog.FINTERNAME = "收款单";
                                    interfaceLog.FInvokeType = "收款单更新";
                                    interfaceLog.Ftoken = "";
                                    interfaceLog.FSTATUS = "失败";
                                    interfaceLog.FRequsetData = json.ToString();
                                    interfaceLog.FReturnData = UpdateJson.ToString();
                                    interfaceLog.FRequest = json.ToString();
                                    interfaceLog.FReturn = UpdateJson.ToString();
                                    string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                    List<string> sqlList = new List<string>();
                                    if (!string.IsNullOrEmpty(LogSql))
                                    {
                                        sqlList.Add(LogSql);
                                    }
                                    //更新单据
                                    string updateSql = string.Format(@"/*dialect*/ update T_AR_RECEIVEBILLENTRY set F_RDLV_CRMDate='{0}',F_RDLV_CRMStatus='{1}' 
                    where fentryid={2}", DateTime.Now, interfaceLog.FSTATUS, FEntryId);

                                    sqlList.Add(updateSql);

                                    DBServiceHelper.ExecuteBatch(this.Context, sqlList);

                                    messbox = messbox + "," + FSEQ;
                                    #endregion
                                }

                            }
                        }
                        if (messbox == "")
                        {
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update T_AR_RECEIVEBILL set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", DateTime.Now, "成功", FID);

                            DBServiceHelper.Execute(this.Context, updateSql);
                            IOperationResult operationResult = new OperationResult();

                            operationResult.OperateResult.Add(new OperateResult()
                            {
                                SuccessStatus = true,
                                Message = string.Format("收款单数据上传成功！"),
                                MessageType = MessageType.Warning,
                                PKValue = 0,
                            });
                            this.OperationResult.MergeResult(operationResult);

                        }
                        else
                        {

                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update T_AR_RECEIVEBILL set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", DateTime.Now, "失败", FID);

                            DBServiceHelper.Execute(this.Context, updateSql);

                            IOperationResult operationResult = new OperationResult();

                            operationResult.OperateResult.Add(new OperateResult()
                            {
                                SuccessStatus = false,
                                Message = string.Format(messbox + "行收款单数据上传失败，请手工同步！"),
                                MessageType = MessageType.Warning,
                                PKValue = 0,
                            });
                            this.OperationResult.MergeResult(operationResult);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// api配置
        /// </summary>
        public DataTable APISetting()
        {
            string Sql = string.Format(@"select * from RDLV_t_CRMInterface");
            return DBServiceHelper.ExecuteDataSet(this.Context, Sql).Tables[0];

        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String Md5(string s)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(s);
            byte[] result = md5.ComputeHash(inputBytes);
            int j = result.Length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = result[i];
                str[k++] = hexDigits[byte0 >> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }
        /**
       * 获取时间戳   格式如：19990101235959
       * @return
       */
        public static String getTimestamp()
        {

            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
        }


    }
}
